const { Add, Update, Exec, QueryOne, QueryById, Exec_Count } = require('../db/dbhelper');
var { init, format } = require('../models/autheducation');
var { peopleQueryOne, peopleUpdate } = require('./people');
var _ = require('underscore');
var { formatDate, formatDateTime } = require('../libs/common');
var { sendMsg } = require('./wechat');
const logger = require('../libs/log').logger;
var moment = require('moment');

//审批
const autheducationAudit = async function (doc) {
  try {
    let { id, ispass, commit } = doc;
    if (!id) {
      return {
        code: 1,
        msg: 'id不能为空'
      }
    }
    if (ispass == null || ispass == undefined) {
      return {
        code: 1,
        msg: 'ispass不能为空'
      }
    }
    // 获取是否有审批记录，如果有，则记录在历史中audithistory
    let audata = await QueryById('hzz_autheducations', doc.id);
    if (audata.audittime) {
      let his = audata.audithistory ? JSON.parse(audata.audithistory) : [];
      his.push({
        ispass: audata.ispass,
        commit: audata.commit,
        audittime: audata.audittime
      });
      doc.audithistory = JSON.stringify(his);
    }
    doc.audittime = new Date();
    let state = await Update('hzz_autheducations', format(doc));
    if (state) {
      // 如果审批通过，同步更新用户认证状态
      if (ispass == 1) {
        let peo = await QueryOne('hzz_peoples',{code: audata.pcode},'reliability');
        await peopleUpdate({ pcode: audata.pcode, cross_education_auth: 1, education: audata.education, university: audata.university, reliability: peo.reliability+30 });
        // 发送认证成功消息
        let send_data = {
          "first": {
            "value": "学历认证",
            "color": "#173177"
          },
          "keyword1": {
            "value": "您提交的学历认证资料，平台已审核通过！",
            "color": "#173177"
          },
          "keyword2": {
            "value": "认证成功",
            "color": "#74BB44"
          },
          "remark": {
            "value": "您可以进行后续操作。",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "学历认证"
          },
          "phrase1": {
            "value": "认证成功"
          },
          "thing4": {
            "value": "您提交的学历认证资料，平台已审核通过"
          },
          "time3": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('realauth_tmpid', send_data, audata.pcode,'myInfo',send_data_red);
      } else {
        // 更新员工学历认证状态为：认证失败
        await peopleUpdate({ pcode: audata.pcode, cross_education_auth: 9 });
        // 发送认证失败消息
        let send_data = {
          "first": {
            "value": "学历认证",
            "color": "#173177"
          },
          "keyword1": {
            "value": "您提交的学历认证资料，平台审核未通过，请重新提交或联系客服咨询！",
            "color": "#173177"
          },
          "keyword2": {
            "value": "认证失败",
            "color": "#e8320e"
          },
          "remark": {
            "value": "请检查提交信息是否完整。",
            "color": "#173177"
          }
        };
        let send_data_red = {
          "thing2": {
            "value": "学历认证"
          },
          "phrase1": {
            "value": "认证失败"
          },
          "thing4": {
            "value": "您提交的学历认证资料，平台审核未通过，请重新提交或联系客服咨询"
          },
          "time3": {
            "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
          }
        };
        sendMsg('realauth_tmpid', send_data, audata.pcode,'myInfo',send_data_red);
      }
      return {
        code: 0,
        msg: '审批完成'
      }
    } else {
      return {
        code: 1,
        msg: '审批异常'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '审批异常'
    }
  }
}
//列表
const autheducationList = async function (doc) {
  try {
    let { ispass, name, pagenum, pagesize } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = 'SELECT * FROM hzz_autheducations WHERE 1=1 ';
    let sql_filter = '';
    if (ispass || ispass == 0) {
      sql_filter += ' AND ispass = ' + ispass;
    }
    if (name) {
      sql_filter += ` AND (nickname LIKE '%${name}%' OR NAME LIKE '%${name}%') `;
    }
    sql += sql_filter;
    sql += ' ORDER BY updatetime DESC,id ASC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `;
    let list = await Exec(sql);

    let pcodes = _.compact(_.pluck(list, 'pcode'));
    let plist = [];
    if (pcodes && pcodes.length) {
      plist = await Exec(`select code,invitcode from hzz_peoples where code in(${pcodes.join(',')})`)
    }
    let tcodes = _.compact(_.pluck(plist, 'invitcode'));
    let tlist = [];
    if (tcodes && tcodes.length) {
      tlist = await Exec(`select name,name_father,code,is_father from hzz_peoples where code in(${tcodes.join(',')})`)
    }
    plist = _.map(plist,function(x){
      let tt= _.find(tlist,function(t){
        return t.code == x.invitcode;
      })
      if(tt){
        x.invitername = tt.is_father ? tt.name_father: tt.name;
      }else{
        x.invitername = '';
      }
      return x;
    })

    list = _.map(list, function (item) {
      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);
      item.audittime = formatDateTime(item.audittime);
      let tiv = _.find(plist,function(t){
        return t.code == item.pcode;
      })
      item.invitername = tiv ? tiv.invitername :'';
      return item;
    });

    let total_sql = 'SELECT count(1) as total FROM hzz_autheducations  WHERE 1=1 ' + sql_filter;
    let total_data = await Exec(total_sql);
    let total = total_data && total_data.length ? total_data[0].total : 0;

    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}
// 立即认证
const autheducationSave = async function (doc) {
  try {
    logger.info('---------------autheducationSave-------------doc:',doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '请重新登录'
      }
    }
    if (!doc.authtype) {
      return {
        code: 1,
        msg: '请选择认证方式'
      }
    }
    if (!doc.university) {
      return {
        code: 1,
        msg: '请输入毕业院校'
      }
    }
    if (!doc.education) {
      return {
        code: 1,
        msg: '请选择学历'
      }
    }
    if (!doc.img) {
      return {
        code: 1,
        msg: '请上传证书照片'
      }
    }
    // 获取用户nickname、name
    let people = await QueryOne('hzz_peoples', { code: doc.pcode }, 'nickname,name');
    if (people) {
      doc.nickname = people.nickname;
      doc.name = people.name;
    }
    let pl = await QueryOne('hzz_autheducations', { pcode: doc.pcode }, null);
    if (pl) {
      doc.id = pl.id;
      await Update('hzz_autheducations', format(doc));
    } else {
      await Add('hzz_autheducations', init(doc));
    }
    // 更新用户学历认证状态为：认证中 0未认证，1认证通过，2：认证中，9认证失败
    peopleUpdate({ pcode: doc.pcode, cross_education_auth: 2 });
    return {
      code: 0,
      msg: '提交成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '提交异常'
    }
  }
}

module.exports = {
  autheducationAudit,
  autheducationList,
  autheducationSave
}